package org.example.demo.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

import java.text.SimpleDateFormat;

/**
 * 提供json和对象相互转换的方法
 */
public class JacksonUtils {
    private static final ObjectMapper objectMapper =
            new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    @SneakyThrows
    public static String toJson(Object object) {
        return objectMapper.writeValueAsString(object);
    }

    @SneakyThrows
    public static <T> T parseObject(String json, Class<T> clazz) {
        return objectMapper.readValue(json, clazz);
    }

    @SneakyThrows
    public static <T> T parseObject(String json, TypeReference<T> typeReference) {
        return objectMapper.readValue(json, typeReference);
    }
}
